/*
 * @Author: Jimmy
 * @LastModifiedBy: Jimmy
 * @Date: 2024-02-23 18:41:13
 * @LastEditTime: 2024-07-07 18:30:55
 * @FilePath: /nest_study/web/src/views/operation/login_log/index.tsx
 */
import { useEffect, useRef, useState } from "react";
import { TOnlineInfo, TOnlineSearch } from "./index.type";
import { Button, DatePicker, Input, message, Modal, Table } from "antd";
import { columns } from "./columns";
import { getRowClassName, getTableScroll } from "@/utils/table";
import PageWrapper from "@/components/page_wrapper";
import TableSearch from "@/components/table_search";
import SearchItem from "@/components/search_item";
import { isValidKey } from "@/utils";
import { remoteList, cleanAll, removeInfo } from "@/api/monitor/login-log";
import { exportFile } from "@/api/monitor/login-log";
import { downloadFile } from "@/utils/download";
import { disabledDate, getNowTimeKey } from "@/utils/date";
const { RangePicker } = DatePicker;
const Post = () => {
  //搜索初始化
  const searchParams: TOnlineSearch = {
    userName: '',
    ip: '',
    startTime: undefined,
    endTime: undefined,
    page: 1,
  }
  const [scrollY, setScrollY] = useState(0)
  const formRef = useRef<any>();
  const [form, setForm] = useState<TOnlineSearch>({ ...searchParams, size: 10 });
  //加载状态
  const [loading, setLoading] = useState<boolean>(false);
  //数据列表
  const [list, setList] = useState<TOnlineInfo[]>([]);
  //数据总数
  const [total, setTotal] = useState<number>(0);
  const [selectedRowKeys, setSelectedRowKeys] = useState<Array<any>>([]);
  const [key,setKey] = useState<string>('');

  useEffect(() => {
    setScrollY(getTableScroll())
    formRef.current = { ...form };
    search();
  }, [])
  //查询列表
  const search = async (page?: number) => {
    setLoading(true);
    setList([])
    try {
      let newForm = { ...form, ...formRef.current }
      if (page) {
        changeItem(page, 'page');
        newForm.page = page;
      };
      let res = await remoteList(newForm);
      let { list, total } = res.data;
      setList(list || []);
      setTotal(total || 0)
    } finally {
      setLoading(false);
    }
  }
  //重置
  const reset = () => {
    for (let k in searchParams) {
      if (isValidKey(k, searchParams)) {
        formRef.current[k] = searchParams[k]
      }
    }
    setKey(getNowTimeKey())
    setForm(formRef.current);
    search(1);
  }
  //删除
  const remove = () => {
    Modal.confirm({
      title: '删除操作',
      content: '确定要删除记录信息？',
      onOk: async () => {
        let ids = [...selectedRowKeys];
        await removeInfo(ids);
        message.success('操作成功');
        search();
        setSelectedRowKeys([]);
      }
    })
  }
  //清空
  const clean = () => {
    Modal.confirm({
      title: '清除操作',
      content: '确定要清除所有记录？',
      onOk: async () => {
        await cleanAll();
        message.success('操作成功');
        search();
        setSelectedRowKeys([]);
      }
    })
  }
  //导出数据
  const download = async () => {
    setLoading(true)
    try {
      let newForm = { ...form, ...formRef.current }
      let res = await exportFile(newForm);
      downloadFile(res, '登录记录', '.xlsx');
      message.success('导出成功！')
    } finally {
      setLoading(false)
    }
  }
  //切换页数
  const changePage = (e: any) => {
    changeItem(e, 'page')
    search(e)
  }
  //参数变化
  const changeItem = (value: any, type: string) => {
    setForm({
      ...form,
      [type]: value
    })
    formRef.current[type] = value
  }
  //多选
  const rowSelection = {
    onChange: (selectedRowKeys: React.Key[], _selectedRows: any[]) => {
      setSelectedRowKeys(selectedRowKeys);
    }
  };
  //选择日期
  const changeDays = (dateStrings: [string, string]) => {
    let startDate = dateStrings[0]
    let endDate = dateStrings[1]
    changeItem(startDate + ' 00:00:00', 'startTime')
    changeItem(endDate + ' 23:59:59', 'endTime')
  }
  //操作
  const TableController = () => {
    return <>
      <Button onClick={() => remove()} type="primary" danger disabled={selectedRowKeys.length ? false : true}>删除记录</Button>
      <Button onClick={() => clean()} danger>清空记录</Button>
      <Button onClick={() => download()} type="primary">导出数据</Button>
    </>
  }

  return (
    <PageWrapper>
      <>
        <TableSearch
          extraComponent={<TableController />}
          search={() => search(1)}
          reset={() => reset()}
        >
          <SearchItem>
            <Input allowClear value={formRef.current?.userName} onChange={(e) => changeItem(e.target.value, 'userName')} placeholder="请输入用户名称" />
          </SearchItem>
          <SearchItem>
            <Input allowClear value={formRef.current?.ip} onChange={(e) => changeItem(e.target.value, 'ip')} placeholder="请输入登录IP地址" />
          </SearchItem>
          <SearchItem>
            <RangePicker key={key} onChange={(_date: any, dateStrings: [string, string]) => changeDays(dateStrings)} disabledDate={disabledDate} />
          </SearchItem>
        </TableSearch>
        <Table
          rowSelection={{
            type: "checkbox",
            columnWidth: 40,
            fixed: 'left',
            ...rowSelection,
            selectedRowKeys: selectedRowKeys
          }}
          columns={columns()}
          dataSource={list}
          loading={loading}
          rowKey={'id'}
          sticky
          virtual
          scroll={{ x: 1000, y: scrollY }}
          rowClassName={getRowClassName}
          pagination={{
            size: formRef.current?.size,
            current: formRef.current?.page,
            total: total,
            showSizeChanger: true,
            onShowSizeChange: (_current: number, size: number) => changeItem(size, 'size'),
            showTotal: () => `共${total} 条`,
          }}
          onChange={(val) => changePage(val.current)}
        ></Table>
      </>
    </PageWrapper>
  )
}

export default Post